package com.situ.vivamarket.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.situ.vivamarket.dao.MemberDao;
import com.situ.vivamarket.model.Member;
import com.situ.vivamarket.model.search.MemberSearchBean;
import com.situ.vivamarket.service.MemberService;
import org.jasypt.util.password.PasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MemberServiceImpl implements MemberService {
    private MemberDao memberDao;
    PasswordEncryptor pe = new StrongPasswordEncryptor();

    @Autowired
    public void setMemberDao(MemberDao memberDao) {
        this.memberDao = memberDao;
    }

    @Override
    public List<Member> getAllMembers(MemberSearchBean msb, Page<?> page) {
        try (Page<?> __ = PageHelper.startPage(page.getPageNum(), page.getPageSize())) {
            return memberDao.findAll(msb);
        }
    }

    @Override
    public int deleteByIds(Integer[] ids) {
        return memberDao.deleteByIds(ids);
    }

    @Override
    public boolean add(Member member) {
        member.setPassword(pe.encryptPassword(member.getPassword()));//加密密码
        member.setCreatedTime(LocalDateTime.now());
        member.setUpdatedTime(LocalDateTime.now());
        return memberDao.insert(member)>0;
    }

    @Override
    public Member findById(Integer id) {
        return memberDao.findById(id);
    }

    @Override
    public Member findByAccount(String account) {
        return memberDao.findByAccount(account);
    }

    @Override
    public boolean update(Member member) {
        if(StringUtils.hasText(member.getPassword())){
            member.setPassword(pe.encryptPassword(member.getPassword()));//加密密码
        }
        member.setUpdatedTime(LocalDateTime.now());
        return memberDao.update(member)>0;
    }
}
